package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author GRS
 * @since 2024/4/19 下午7:51
 */
@RestController
@RequestMapping("/dish")
public class DishController
{
    @Resource
    private DishService dishService;

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDTO dishDTO)
    {
        dishService.saveWithFlavors(dishDTO);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     */
    @GetMapping("/page")
    public R<IPage<DishDTO>> page(int page, int pageSize, String name)
    {
        // 构造分页构造器对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDTO> dishDTOPage = new Page<>();

        // 构造条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        // 添加过滤条件
        wrapper.like(name != null, Dish::getName, name)
            .orderByDesc(Dish::getUpdateTime);

        IPage<Dish> modelPage = dishService.page(dishPage, wrapper);

        // 对象拷贝
        BeanUtils.copyProperties(modelPage, dishDTOPage, "records");
        List<Dish> records = dishPage.getRecords();
        List<DishDTO> dishDTOList = records.stream().map(item ->
        {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);
            Long categoryId = item.getCategoryId();
            // 根据ID查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null)
            {
                String categoryName = category.getName();
                dishDTO.setCategoryName(categoryName);
            }
            return dishDTO;
        }).toList();

        dishDTOPage.setRecords(dishDTOList);

        return R.success(dishDTOPage);
    }

    /**
     * 根据ID查询菜品信息和对应的口味信息
     */
    @GetMapping("/{id}")
    public R<DishDTO> get(@PathVariable("id") Long id)
    {
        DishDTO dishDTO = dishService.getByIdWithFlavors(id);
        return R.success(dishDTO);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDTO dishDTO)
    {
        dishService.updateWithFlavors(dishDTO);

        // 清理所有菜品的缓存数据
        // Set<String> keys = redisTemplate.keys("dish_*");
        // redisTemplate.delete(keys);

        // 清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDTO.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("更新菜品成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     */
    @GetMapping("/list")
    public R<List<DishDTO>> list(Dish dish)
    {
        /*
         * // 构造查询条件
         * LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
         * wrapper
         *     .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
         *     // 添加条件，查询状态为1（起售状态）的菜品
         *     .eq(Dish::getStatus, 1)
         *     .orderByAsc(Dish::getSort)
         *     .orderByDesc(Dish::getUpdateTime);
         *  List<Dish> list = dishService.list(wrapper);
         */
        List<DishDTO> dishDTOList;

        // 动态构造Key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        // 先从Redis中查询缓存数据
        // dishDTOList = JSON.parseArray(redisTemplate.opsForValue().get(key) + "", DishDTO.class);
        dishDTOList = (List<DishDTO>) redisTemplate.opsForValue().get(key);

        // 如果存在，直接返回，无需查询数据库
        if (dishDTOList != null)
            return R.success(dishDTOList);

        // 如果不存在，需要查询数据库
        // 构造查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper
            .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
            // 添加条件，查询状态为1（起售状态）的菜品
            .eq(Dish::getStatus, 1)
            .orderByAsc(Dish::getSort)
            .orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);
        dishDTOList = list
            .stream()
            .map(item ->
            {
                DishDTO dishDTO = new DishDTO();
                BeanUtils.copyProperties(item, dishDTO);
                Long categoryId = item.getCategoryId();
                // 根据ID查询分类对象
                Category category = categoryService.getById(categoryId);
                if (category != null)
                {
                    String categoryName = category.getName();
                    dishDTO.setCategoryName(categoryName);
                }
                // 当前菜品ID
                Long dishId = item.getId();
                LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DishFlavor::getDishId, dishId);
                List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
                dishDTO.setFlavors(flavors);

                return dishDTO;
            })
            .toList();
        // 将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key, dishDTOList, 1, TimeUnit.HOURS);

        return R.success(dishDTOList);
    }
}